package org.seven.jrdp.web.t;

import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.seven.jrdp.biz.t.model.TRkd;
import org.seven.jrdp.biz.t.service.TRkdService;
import org.seven.jrdp.commons.exception.WebException;
import org.seven.jrdp.commons.model.Option;
import org.seven.jrdp.commons.model.Result;
import org.seven.jrdp.commons.mybatis.model.PageRequest;
import org.seven.jrdp.commons.util.Excel2007Utils;
import org.seven.jrdp.commons.util.ServletUtils;
import org.seven.jrdp.commons.util.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageInfo;

@RestController
@RequestMapping("/mgt/t/rkd")
public class TRkdController {
	private static final String EXCEL_RKD = "rkd.xlsx";
	private static final String EXCEL_RKMB = "rkmb.xlsx";
	@Autowired
	private TRkdService tRkdService;

	@GetMapping("/{view}")
	public ModelAndView view(@PathVariable String view) {
		return new ModelAndView("mgt/t/rkd/rkd_" + view);
	}

	@PostMapping("/find")
	public PageInfo<Map<String, Object>> find(PageRequest pageRequest, HttpServletRequest request) {
		Map<String, Object> map = ServletUtils.getSearchParams(request);
		PageInfo<Map<String, Object>> page = tRkdService.find(map, pageRequest);
		return page;
	}

	@RequestMapping("/wcrk")
	public Result wcrk(String cpbh) {
		tRkdService.wcrk(cpbh);
		return Result.SUCCESS;
	}

	@RequestMapping("/qxwc")
	public Result qxwc(String cpbh) {
		tRkdService.qxwc(cpbh);
		return Result.SUCCESS;
	}

	@RequestMapping("/get")
	public TRkd get(String id) {
		TRkd tRkd = tRkdService.get(id);
		return tRkd;
	}

	@RequestMapping("/kccpxh/{cpbh}")
	public List<Option> kccpxh(@PathVariable String cpbh) {
		List<Option> list = tRkdService.findKcCpxh(cpbh);
		return list;
	}

	@RequestMapping("/cpxh/{cpbh}")
	public List<Option> cpxh(@PathVariable String cpbh) {
		List<Option> list = tRkdService.findCpxh(cpbh);
		return list;
	}

	@PostMapping("/xgrkd")
	public Result xgrkd(String cpbh1, String cpbh, Date rkrq) {
		tRkdService.xgrkd(cpbh1, cpbh, rkrq, ShiroUtils.getUser().getId());
		return Result.SUCCESS;
	}

	@PostMapping("/xgrkmx")
	public Result xgrkmx(String cpbh, String cpxh, int ks) {
		tRkdService.xgrkmx(cpbh, cpxh, ks);
		return Result.SUCCESS;
	}

	@RequestMapping(value = "/download")
	public void download(HttpServletRequest request, HttpServletResponse response) {
		File file = new File(ServletUtils.getExcelPath(EXCEL_RKMB));
		ServletUtils.download(file, "入库模版.xlsx", request, response);
	}

	@PostMapping(value = "/upload")
	public Result upload(MultipartFile file, HttpServletResponse response) {
		if (!file.getOriginalFilename().toLowerCase().endsWith(".xlsx")) {
			throw new WebException("请上传扩展名为.xlsx的文件");
		}
		byte[] in = null;
		try {
			in = file.getBytes();
		} catch (Exception ex) {
			throw new WebException("获取文件失败");
		}
		List<String[]> list = new ArrayList<String[]>();
		Workbook workbook = Excel2007Utils.getWorkbook(in);
		Sheet sheet = workbook.getSheet("Sheet1");
		int rownum = 1;
		while (true) {
			int cellnum = 0;
			try {
				Row row = sheet.getRow(rownum);
				if (null == row) {
					break;
				}
				String[] text = new String[7];
				int i = 0;
				for (cellnum = 0; cellnum <= 6; cellnum++) {
					Cell cell = row.getCell(cellnum);
					if (null == cell) {
						text[i] = "";
					} else {
						text[i] = cell.getStringCellValue().trim();
					}
					i++;
				}
				list.add(text);
				rownum++;
			} catch (Exception ex) {
				throw new WebException("第" + (rownum + 1) + "行、第" + (cellnum + 1) + "列读取失败，请数据检查格式");
			}
		}
		tRkdService.upload(list);
		return Result.SUCCESS;
	}

	@RequestMapping("/dy")
	public void dy(String cpbh, PageRequest pageRequest, HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = tRkdService.getDy(cpbh, pageRequest);
		Workbook workbook = Excel2007Utils.getWorkbook(ServletUtils.getExcelPath(EXCEL_RKD));
		dy(workbook, map);
		String fileName = cpbh + "(第" + pageRequest.getPage() + "页)" + Excel2007Utils.SUFFIX;
		ServletUtils.download(workbook, fileName, request, response);
	}

	@SuppressWarnings("unchecked")
	private void dy(Workbook workbook, Map<String, Object> map) {
		Sheet sheet = workbook.getSheetAt(0);
		String title = "①成品铝锭（" + map.get("ggxh") + "）入库附页——原料课填写";
		sheet.getRow(1).getCell(0).setCellValue(title);
		sheet.getRow(31).getCell(1).setCellValue((Integer) map.get("zl"));
		sheet.getRow(32).getCell(1).setCellValue((Integer) map.get("ks"));
		List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("list");
		int row = 2;
		int col = 1;
		for (Map<String, Object> dy : list) {
			sheet.getRow(row).getCell(col).setCellValue(DateFormatUtils.format((Timestamp) dy.get("rkrq"), "yyyy.MM.dd"));
			sheet.getRow(row + 1).getCell(col).setCellValue((String) dy.get("cpbh"));
			sheet.getRow(row + 2).getCell(col).setCellValue((Integer) dy.get("ks"));
			sheet.getRow(row + 3).getCell(col).setCellValue((String) dy.get("kqmc"));
			sheet.getRow(row + 28).getCell(col).setCellValue((Integer) dy.get("zl"));
			List<Map<String, Object>> dymx = (List<Map<String, Object>>) dy.get("dymx");
			int i = 5;
			for (Map<String, Object> mx : dymx) {
				sheet.getRow(row + i).getCell(col - 1).setCellValue((String) mx.get("cpxh"));
				sheet.getRow(row + i).getCell(col).setCellValue((Integer) mx.get("zl"));
				sheet.getRow(row + i).getCell(col + 1).setCellValue((Integer) mx.get("ks"));
				++i;
			}
			col += 6;
		}
	}
}